using System;
using Symbonix.Library.DataStructure;
using System.Web.Security;
using System.Collections.Generic;
using Symbonix.Library.Web.Security.DAL.Repositories;
using System.Collections;
using NHibernate.Mapping;
using Symbonix.Library.Web.Security.DAL.Entities;
namespace Symbonix.NorSoNet.Security.BLL.Membership
{

    public class Admin : SystemUser
    {

        protected Admin() { }

        /// <summary>
        /// Constructor that copy a SystemUser instance to Admin instance
        /// [Jalal]
        /// </summary>
        /// <param name="systemUser">Instance to use for copy</param>
        internal Admin(IUser systemUser)
        {
            this.Comment = systemUser.Comment;
            this.CreationDate = systemUser.CreationDate;
            this.Email = systemUser.Email;
            this.FirstName = systemUser.FirstName;
            this.Id = systemUser.Id;
            this.IsApproved = systemUser.IsApproved;
            this.IsLockedOut = systemUser.IsLockedOut;
            this.LastActivityDate = systemUser.LastActivityDate;
            this.LastLockoutDate = systemUser.LastLockoutDate;
            this.LastLoginDate = systemUser.LastLoginDate;
            this.LastName = systemUser.LastName;
            this.LastPasswordChangedDate = systemUser.LastPasswordChangedDate;
            this.UserName = systemUser.UserName;
        }

        protected internal static new IUser GetInstance() { return new Admin(); }

        public virtual ReadWriteCustomCollection<IUser> GetAllUsersByRole(String roleName, String orderBy, bool ascendingSort, int selectedIndex, int pageSize, out int totalItems)
        {
            throw new System.Exception("Not implemented");
        }

        public virtual ReadWriteCustomCollection<IUser> GetAllUsers(String orderBy, bool ascendingSort, int selectedIndex, int pageSize, out int totalItems)
        {
            ReadWriteCustomCollection<IUser> userCollection = new ReadWriteCustomCollection<IUser>();

            UserRepository userRepository = new UserRepository();
            IList userList = userRepository.GetAll(orderBy, ascendingSort, true, selectedIndex, pageSize, out totalItems);

            foreach (User user in userList)
            {
                userCollection.Add(GetBizUserFromEntity(user));
            }
            return userCollection;

        }

        /// <summary>
        /// this function will send a business user instanace from entity user
        /// </summary>
        /// <param name="user">user object of entity</param>
        /// <returns></returns>
        private IUser GetBizUserFromEntity(User user)
        {
            IUser bizUser = ModuleManager.MembershipFactory.GetUser();
            bizUser.UserName = user.UserName;
            bizUser.Id = user.UserID;
            bizUser.Email = user.Email;
            bizUser.FirstName = user.FirstName;
            bizUser.LastName = user.LastName;
            bizUser.Comment = user.Comment;
            bizUser.IsApproved = user.IsApproved;
            bizUser.IsLockedOut = user.IsLocked;
            bizUser.CreationDate = user.CreateDate;
            bizUser.LastLoginDate = user.LastLoginDate.Value;
            bizUser.LastActivityDate = user.LastActivityDate.Value;
            bizUser.LastPasswordChangedDate = user.LastPasswordChangeDate.Value;
            bizUser.LastLockoutDate = user.LastLockoutDate.Value;
            return bizUser;
        }

        public virtual bool DeleteUser(int userId)
        {
            throw new System.Exception("Not implemented");
        }

        public virtual bool DeleteUser(IUser user)
        {
            throw new System.Exception("Not implemented");
        }

        /// <summary>
        /// Toggles IsActive status of a user account
        /// and returns the current status
        /// </summary>
        /// <param name="userId">User id for which to toggle the status</param>
        /// <returns>Returns current active status of the user</returns>
        public virtual bool ToggleUserActiveStatus(int userId)
        {
            throw new System.Exception("Not implemented");
        }

        /// <summary>
        /// Toggles IsActive status of a user account
        /// and returns the current status [Jalal]
        /// </summary>
        /// <param name="user">User for which to toggle the status</param>
        /// <returns>Returns current active status of the user</returns>
        public virtual bool ToggleUserActiveStatus(IUser user)
        {
            if (user != null)
                return ToggleUserActiveStatus(user.Id);
            else
                throw new ArgumentNullException("user");
        }

        /// <summary>
        /// Creates a new user instance using membership provider
        /// [Jalal]
        /// </summary>
        /// <param name="userName">Unique username</param>
        /// <param name="password">Password according to password policy</param>
        /// <param name="email">User email</param>
        /// <param name="firstName">User first name</param>
        /// <param name="lastName">User last name</param>
        /// <param name="role">User role</param>
        /// <param name="isApproved">User approve status</param>
        /// <param name="status">Out parameter for indication of account creation status</param>
        /// <returns>Returns created user instance, supplied by membership provider</returns>
        public override IUser Create(string userName, string password, string email, string firstName, string lastName, string role, bool isApproved, out MembershipCreateStatus status)
        {
            status = MembershipCreateStatus.ProviderError;

            MembershipUser user = System.Web.Security.Membership.Providers[role].CreateUser(userName, password, email, string.Empty, string.Empty, isApproved, null, out status);
            Roles.Provider.AddUsersToRoles(new string[] { user.UserName }, new string[] { role });
            UserRepository ur = new UserRepository();
            // user.ProviderUserKey
            User dbUser = ur.GetByPrimaryKey(Int32.Parse(user.ProviderUserKey.ToString()));
            dbUser.FirstName = firstName;
            dbUser.LastName = lastName;
            ur.Update(dbUser);
            return base.LoadFromMembershipUser(user, firstName, lastName);

        }
    }
}
